# lianjie.py (PyMySQL 版本)
import pymysql
from pymysql import Error

def connect_mysql():
    try:
        conn = pymysql.connect(
            host='localhost',
            user='root',
            password='123456',
            port=3306,
            charset='utf8mb4',
            database='xm',
            cursorclass=pymysql.cursors.DictCursor
        )
        print("✅ 成功连接! MySQL版本:", conn.get_server_info())
        # 可选示例：列出数据库
        with conn.cursor() as cursor:
            cursor.execute("SHOW DATABASES")
            print("📦 数据库列表:", [db['Database'] for db in cursor.fetchall()])
        return conn
    except Error as e:
        print("❌ 连接失败:", e)
        return None

# 测试用例
if __name__ == "__main__":
    conn = connect_mysql()
    if conn:
        # 做点什么，比如查询表
        with conn.cursor() as cursor:
            cursor.execute("SHOW TABLES")
            print("📋 表列表:", [t for t in cursor.fetchall()])
        conn.close()
